package org.lsms.servlet;

/**
 * servlet used to send notify mail to paper authors
 * @author ZhanXueliang
 * 2010.9.11
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lsms.dao.impl.DaoImpl;
import org.lsms.mail.MailSenderInfo;
import org.lsms.mail.SimpleMailSender;

public class send_notify_mail extends HttpServlet {

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doPost(request, response);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			
			int type = Integer.parseInt(request.getParameter("type"));
			int start_id = Integer.parseInt(request.getParameter("start_id"));
			System.out.println(type);
			
			DaoImpl impl = new DaoImpl();
			
			HashMap<Integer,String> map = impl.get_paper_contact_mail(type,start_id);
			Set<Integer> set = map.keySet();
			Iterator it = set.iterator();
			
			MailSenderInfo mailInfo = new MailSenderInfo();
			mailInfo.init(mailInfo);
			mailInfo.setSubject("Send notify mail");
			
			if(type==0){
				mailInfo.setContent(impl.get_mail_content(7));
			}else if(type==1){
				mailInfo.setContent(impl.get_mail_content(5));
			}else{
				mailInfo.setContent(impl.get_mail_content(6));
			}
			
			while(it.hasNext()){
				Integer paper_id = (Integer)it.next();
				String email = map.get(paper_id);
				mailInfo.setToAddress(email);
				mailInfo.setSubject(paper_id.toString());
				
				SimpleMailSender sms = new SimpleMailSender();
				
				if(sms.sendTextMail(mailInfo)){
					continue;
				}else{
					String info = "Problem occurs when sending mail to the " +
							"contact author of paper "+paper_id+". His/Her " +
									"Email address is "+email+".";
					response.sendRedirect("admin/admin_show_info.jsp?admin_info="+info);
				}
			}
			
			String info = "All mails have been sent succussfully!";
			response.sendRedirect("admin/admin_show_info.jsp?admin_info="+info);
			
	}

	public void init() throws ServletException {

	}

}
